package com.example.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;

public class DemoHttpServletWrapper extends HttpServletRequestWrapper {

    private Map<String,Object> params;

    public DemoHttpServletWrapper(HttpServletRequest request) {
        super(request);
        String reqMessage = request.getParameter("req_message");
        JSONObject json = JSONObject.parseObject(reqMessage);
        Map<String,Object> eval = (Map<String,Object>) JSONPath.eval(json, "$.req_body");

        if (CollectionUtils.isEmpty(eval)) {
            params = new HashMap<>(0);
            return;
        }

        this.params = eval;

    }

    @Override
    public String getQueryString() {
        String collect = this.params.entrySet().stream().map(x -> x.getKey() + "=" + x.getValue()).collect(Collectors.joining("&"));
        System.out.println(collect);

        return super.getQueryString();
    }


    @Override
    public String getParameter(String name) {
        return this.params.get(name) == null? null : this.params.get(name).toString();
    }

    @Override
    public Map<String, String[]> getParameterMap() {

        return getMapParams();
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(this.params.keySet());
    }

    @Override
    public String[] getParameterValues(String name) {
        return getMapParams().get(name);
    }

    @Override
    public int getContentLength() {
      return getByteLength();
    }

    @Override
    public long getContentLengthLong() {
        return getByteLength();
    }

    private byte[] getByte(){
        return JSON.toJSONString(this.params).getBytes(Charset.forName("UTF-8"));
    }

    private int getByteLength(){
        return getByte().length;
    }


    private Map<String,String[]> getMapParams(){
        Map<String,String[]> map = new HashMap<>();
        for (Map.Entry<String, Object> entry : this.params.entrySet()) {
            String key = entry.getKey();
            Object value =  entry.getValue();
            if (entry.getValue() instanceof String[]) {
                map.put(key,(String[])value);
            }else{
                map.put(key,new String[]{value.toString()});
            }
        }
        return map;
    }


}
